package com.qf.zuoye0620.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;

/**
 * @Author UNIQ7xi
 * @Date 2023/6/20 19:41
 * @Version v1.8
 **/
public class JWTUtils {
    private static final String SECRET_KEY = "secret"; // 秘钥，应该从环境变量或配置文件中读取

    public static String generateToken(Long userId, String username) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + 3600000); // 过期时间为1小时后

        Key key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

        String token = Jwts.builder()
                .setId(userId.toString())
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(key)
                .compact();

        return token;
    }
}
